package app.framework.freemarker.util;

import app.framework.freemarker.model.CurrentLangMethodModel;
import app.framework.freemarker.model.I18nJsMethodModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.ErrorUtil;

import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 渲染 JS 脚本的工具类。
 * </p>
 *
 * @author mh.z
 */
public class RenderJsUtil {
    private static final Map<String, Object> DATA_MODEL;

    static {
        DATA_MODEL = new HashMap<>();
        initUtil(RenderUtilConfig.createDefault());
    }

    public static void initUtil(RenderUtilConfig config) {
        DATA_MODEL.put("t", new I18nJsMethodModel());
        DATA_MODEL.put("currentLang", new CurrentLangMethodModel());
    }

    /**
     * 渲染内容
     *
     * @param cfg
     * @param writer
     * @param name
     */
    public static void renderContent(Configuration cfg, Writer writer, String name) {
        CheckUtil.notNull(cfg, "cfg null");
        CheckUtil.notNull(writer, "writer null");
        CheckUtil.notNull(name, "name null");

        try {
            Template template = cfg.getTemplate(name);
            template.process(DATA_MODEL, writer);
        } catch (Exception e) {
            throw ErrorUtil.sneakyError(e);
        }
    }

}
